package com.visitor.registration.service.impl;

import com.visitor.registration.dto.VisitorDTO;
import com.visitor.registration.entity.City;
import com.visitor.registration.entity.InterestArea;
import com.visitor.registration.entity.Province;
import com.visitor.registration.entity.Visitor;
import com.visitor.registration.entity.VisitorInterest;
import com.visitor.registration.entity.Type;
import com.visitor.registration.mapper.CityMapper;
import com.visitor.registration.mapper.InterestAreaMapper;
import com.visitor.registration.mapper.ProvinceMapper;
import com.visitor.registration.mapper.TypeMapper;
import com.visitor.registration.mapper.VisitorInterestMapper;
import com.visitor.registration.mapper.VisitorMapper;
import com.visitor.registration.service.VisitorService;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class VisitorServiceImpl implements VisitorService {

    @Autowired
    VisitorMapper visitorMapper;
    @Autowired
    ProvinceMapper provinceMapper;
    @Autowired
    CityMapper cityMapper;
    @Autowired
    InterestAreaMapper interestAreaMapper;
    @Autowired
    VisitorInterestMapper visitorInterestMapper;
    @Autowired
    TypeMapper typeMapper;
    @Autowired
    JavaMailSender mailSender;
    
    @Value("${spring.mail.to}")
    private String toEmail;
    
    @Value("${app.excel.dir}")
    private String excelDir;
    
    @Override
    @Transactional
    public Visitor saveVisitor(VisitorDTO visitorDTO) {
        // 创建访客对象
        Visitor visitor = new Visitor();
        visitor.setName(visitorDTO.getName());
        visitor.setPhone(visitorDTO.getPhone());
        visitor.setCompany(visitorDTO.getCompany());
        visitor.setPosition(visitorDTO.getPosition());
        visitor.setType(visitorDTO.getType());
        visitor.setTypeId(visitorDTO.getTypeId());
        visitor.setProvinceId(visitorDTO.getProvinceId());
        visitor.setCityId(visitorDTO.getCityId());
        visitor.setCreatedAt(LocalDateTime.now());
        
        // 插入访客信息
        visitorMapper.insert(visitor);
        
        // 设置关联信息
        if (visitorDTO.getProvinceId() != null) {
            Province province = provinceMapper.selectById(visitorDTO.getProvinceId());
            visitor.setProvince(province);
        }
        
        if (visitorDTO.getCityId() != null) {
            City city = cityMapper.selectById(visitorDTO.getCityId());
            visitor.setCity(city);
        }
        
        if (visitorDTO.getTypeId() != null) {
            Type type = typeMapper.selectById(visitorDTO.getTypeId());
            visitor.setTypeObj(type);
        }
        
        // 设置关注领域
        if (visitorDTO.getInterestAreaIds() != null && !visitorDTO.getInterestAreaIds().isEmpty()) {
            ArrayList<VisitorInterest> visitorInterests = new ArrayList<VisitorInterest>();
            for (Integer interestId : visitorDTO.getInterestAreaIds()) {
                VisitorInterest vi = new VisitorInterest();
                vi.setVisitorId(visitor.getId());
                vi.setInterestId(interestId);
                visitorInterests.add(vi);
            }
            visitorInterestMapper.batchInsert(visitorInterests);
            
            // 获取关注领域详情
            List<InterestArea> interestAreas = interestAreaMapper.selectByVisitorId(visitor.getId());
            visitor.setInterestAreas(interestAreas);
        }
        
        return visitor;
    }
    
    @Override
    public List<Visitor> getAllVisitors() {
        return visitorMapper.selectAll();
    }
    
    @Override
    public List<Visitor> getVisitorsByDateRange(LocalDateTime start, LocalDateTime end) {
        return visitorMapper.selectByDateRange(start, end);
    }
    
    @Override
    public void generateReportAndSendMail() throws Exception {
        // 获取当天的访客信息
        LocalDateTime today = LocalDateTime.now().toLocalDate().atStartOfDay();
        LocalDateTime tomorrow = today.plusDays(1);
        List<Visitor> visitors = visitorMapper.selectByDateRange(today, tomorrow);
        
        // 为每个访客加载详细信息
        for (Visitor visitor : visitors) {
            if (visitor.getProvinceId() != null) {
                visitor.setProvince(provinceMapper.selectById(visitor.getProvinceId()));
            }
            if (visitor.getCityId() != null) {
                visitor.setCity(cityMapper.selectById(visitor.getCityId()));
            }
            visitor.setInterestAreas(interestAreaMapper.selectByVisitorId(visitor.getId()));
        }
        
        // 生成Excel
        String dateStr = today.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String fileName = "访客登记表_" + dateStr + ".xlsx";
        
        // 确保目录存在
        File dir = new File(excelDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        String filePath = excelDir + File.separator + fileName;
        
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("访客信息");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            String[] columns = new String[] {"序号", "姓名", "手机号", "公司", "职位", "类型", "省份", "城市", "关注领域", "登记时间"};
            for (int i = 0; i < columns.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(columns[i]);
                cell.setCellStyle(headerStyle);
            }
            
            // 填充数据
            int rowNum = 1;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (Visitor visitor : visitors) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(rowNum - 1);
                row.createCell(1).setCellValue(visitor.getName());
                row.createCell(2).setCellValue(visitor.getPhone());
                row.createCell(3).setCellValue(visitor.getCompany() != null ? visitor.getCompany() : "");
                row.createCell(4).setCellValue(visitor.getPosition() != null ? visitor.getPosition() : "");
                row.createCell(5).setCellValue(visitor.getType());
                row.createCell(6).setCellValue(visitor.getProvince() != null ? visitor.getProvince().getName() : "");
                row.createCell(7).setCellValue(visitor.getCity() != null ? visitor.getCity().getName() : "");
                
                // 关注领域
                String interests = visitor.getInterestAreas() != null ? 
                    visitor.getInterestAreas().stream()
                        .map(InterestArea::getName)
                        .collect(Collectors.joining(", ")) : "";
                row.createCell(8).setCellValue(interests);
                
                row.createCell(9).setCellValue(visitor.getCreatedAt().format(formatter));
            }
            
            // 自动调整列宽
            for (int i = 0; i < columns.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 保存Excel文件
            try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
                workbook.write(outputStream);
            }
            
            // 发送邮件
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            
            // 支持多个收件人
            String[] toEmails = toEmail.split(",");
            helper.setTo(toEmails);
            
            // 设置发件人地址，必须与认证用户名相同
            helper.setFrom("dengjiahao@thoven-dm.com");
            
            helper.setSubject("访客登记表 - " + dateStr);

            // 使用普通字符串拼接
            String emailText = "特霍芬工作人员：\n\n\n\n" +
                "请查收今日（" + today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "）展会意向客户登记表，详情见附件。\n\n" +
                "此邮件为系统自动发送，请勿直接回复。";

            helper.setText(emailText, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            helper.addAttachment(fileName, file);

            mailSender.send(message);
        }
    }
    
    @Override
    public List<Province> getAllProvinces() {
        return provinceMapper.selectAll();
    }
    
    @Override
    public List<City> getCitiesByProvinceId(Integer provinceId) {
        return cityMapper.selectByProvinceId(provinceId);
    }
    
    @Override
    public List<InterestArea> getAllInterestAreas() {
        return interestAreaMapper.selectAll();
    }
    
    @Override
    public List<Type> getAllTypes() {
        return typeMapper.selectAll();
    }
}